package com.bond.jumper.common.encode;

import com.bond.jumper.common.po.MessageToServer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

/**
 * 客户端编码消息
 */
public class MessageToServerEncoder extends MessageToByteEncoder<MessageToServer> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, MessageToServer messageToServer, ByteBuf byteBuf) throws Exception {
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {

            objectOutputStream.writeObject(messageToServer);
            byte[] bytes = byteArrayOutputStream.toByteArray();

            //写入数据长度
            byteBuf.writeInt(bytes.length);
            //然后写入序列化后的数据
            byteBuf.writeBytes(bytes);
        }
    }
}
